package com.buttonpay.home;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.UnknownHostException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.view.FocusFinder;
import android.widget.Toast;
import com.buttonpay.AppData;
import com.buttonpay.MD5Generator;
import com.buttonpay.Products;
import com.buttonpay.R;
  
public class TopUpProcess 
{
	Context context;
	ProgressDialog pd;
	Handler handler;
	Products currentProduct;
	String checksum;
	String amount,refMobileno,fromMoNo;
	HttpClient httpclient = new DefaultHttpClient();
	HttpPost httppost = new HttpPost(AppData.hostURL+"/WebService/iTopUp/agentapp.php");
	TopUpStatus topUpStatus;
	MD5Generator generator=new MD5Generator();
	
	public TopUpProcess(Context context, ProgressDialog pd, Handler handler, Products currentProdut, String refmobileNo, String fromMoNo,String amount) 
	{
		// TODO Auto-generated constructor stub
		this.context=context;
		this.pd=pd;
		this.handler=handler;
		this.currentProduct=currentProdut;
		this.refMobileno=refmobileNo;
		this.fromMoNo=fromMoNo;
		this.amount=""+Integer.parseInt(amount)*100;
	}

	public TopUpStatus process()  
	{
		
		if(currentProduct.getProductType().equals("0"))
		{
					//openRecharge
					 
					
					String checksumString=AppData.getUserInfo().getLoginID()+"|"+
		                      currentProduct.getBatchID()+"|"+
		                      currentProduct.getSystemServiceID()+"|"+
		                      refMobileno+"|"+
		                      amount+"|"+
		                      fromMoNo+"|"+
		                      ""+"|"+
		                      AppData.getUserInfo().getpublickey();
		
					System.out.println("Check sum string===>"+checksumString);
					
					String Checksum = null;
					try 
					{
						Checksum = generator.MD5(generator.SHA1(checksumString));
					}
					catch (NoSuchAlgorithmException e) 
					{
						e.printStackTrace();
					} 
					catch (UnsupportedEncodingException e) 
					{
						e.printStackTrace();
					}
					System.out.println("Final Checksum:"+Checksum);
					
					
					try 
					{
				        // Add your data
				        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				        nameValuePairs.add(new BasicNameValuePair("function", "OpenRecharge"));
				        nameValuePairs.add(new BasicNameValuePair("LoginId", AppData.getUserInfo().getLoginID()));
				        nameValuePairs.add(new BasicNameValuePair("BatchId", currentProduct.getBatchID()));
				        nameValuePairs.add(new BasicNameValuePair("SystemServiceID", currentProduct.getSystemServiceID()));
				        nameValuePairs.add(new BasicNameValuePair("ReferalNumber", refMobileno));
				        nameValuePairs.add(new BasicNameValuePair("Amount", amount));
				        nameValuePairs.add(new BasicNameValuePair("FromANI", fromMoNo));
				        nameValuePairs.add(new BasicNameValuePair("Email", ""));
				        nameValuePairs.add(new BasicNameValuePair("Checksum",Checksum)); 
				        
				        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		
				        ResponseHandler<String> responseHandler = new BasicResponseHandler();
				        // Execute HTTP Post Request
				        System.out.println("\nReference Mobile No:"+ refMobileno+
											"\nFrom Mobile No:"+fromMoNo+
											"\namount:"+amount);

				        String response = httpclient.execute(httppost,responseHandler);
				        System.out.println("Response:"+response);
				        JSONParser jsonParser=new JSONParser(response);
				        topUpStatus=jsonParser.parse();
				        
				        return topUpStatus;
				    }
					catch (final ClientProtocolException e) 
					{
				        // TODO Auto-generated catch block
						handler.post(new Runnable()
						{
							
							public void run() 
							{
								// TODO Auto-generated method stub
								pd.dismiss();
								Toast.makeText(context,context.getString(R.string.conn_msg),Toast.LENGTH_LONG).show(); 
							}
						});
						return null;
				    }
					
					catch (final IOException e) 
					{
						handler.post(new Runnable()
						{
							
							public void run() 
							{
								// TODO Auto-generated method stub
								pd.dismiss();
								Toast.makeText(context, context.getString(R.string.conn_msg),Toast.LENGTH_LONG).show();
							}
						});
						return null;
				    }  
		}
		else if(currentProduct.getProductType().equals("1"))
		{
			 //closerecharge
					
					String checksumString=AppData.getUserInfo().getLoginID()+"|"+
		                    		      currentProduct.getBatchID()+"|"+
		                    		      currentProduct.getSystemServiceID()+"|"+
						                  refMobileno+"|"+
						                  fromMoNo+"|"+
						                  ""+"|"+
						                  AppData.getUserInfo().getpublickey();
					
					System.out.println("Check sum string===>"+checksumString);
					
					String Checksum = null;
					try {
						Checksum = generator.MD5(generator.SHA1(checksumString));
					} catch (NoSuchAlgorithmException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (UnsupportedEncodingException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					System.out.println("Final Checksum:"+Checksum);
					try 
					{ 
							List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
							nameValuePairs.add(new BasicNameValuePair("function", "CloseRecharge"));
						    nameValuePairs.add(new BasicNameValuePair("LoginId", AppData.getUserInfo().getLoginID()));
						    nameValuePairs.add(new BasicNameValuePair("BatchId", currentProduct.getBatchID()));
						    nameValuePairs.add(new BasicNameValuePair("SystemServiceID", currentProduct.getSystemServiceID())); 
						    nameValuePairs.add(new BasicNameValuePair("ReferalNumber", refMobileno));
						    nameValuePairs.add(new BasicNameValuePair("FromANI", fromMoNo));
						    nameValuePairs.add(new BasicNameValuePair("Email", ""));
						    nameValuePairs.add(new BasicNameValuePair("Checksum",Checksum));
						    
						    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
						    
						    ResponseHandler<String> responseHandler = new BasicResponseHandler();
						    
						    System.out.println("\nRefMobile No:"+ refMobileno+
												"\nFrom MobileNo:"+fromMoNo+
												"\namount:"+amount);
				
						    
							String response = httpclient.execute(httppost,responseHandler);
							System.out.println("Response:"+response);
						    
							JSONParser jsonParser=new JSONParser(response);						    
							topUpStatus=jsonParser.parse();						        
							
							return topUpStatus;
							
					} 
					catch(UnknownHostException e)
					{
						
						handler.post(new Runnable()
						{
							
							public void run() 
							{
								// TODO Auto-generated method stub
								pd.dismiss();
								Toast.makeText(context,context.getString(R.string.conn_msg),Toast.LENGTH_LONG).show(); 
							}
						});
						return null;
					}
					catch (final ClientProtocolException e) 
					{
				        // TODO Auto-generated catch block
							handler.post(new Runnable()
							{
								
								public void run() 
								{
									// TODO Auto-generated method stub
									pd.dismiss();
									Toast.makeText(context,context.getString(R.string.conn_msg),Toast.LENGTH_LONG).show(); 
								}
							});
							return null;
				    }
					
					catch (final IOException e) 
					{
							handler.post(new Runnable()
							{
								
								public void run() 
								{
									// TODO Auto-generated method stub
									pd.dismiss();
									Toast.makeText(context, e.getMessage(),Toast.LENGTH_LONG).show();
								}
							});
							return null;
				    }  
		}//else block over 
		
		return null;
		
	}

	private class JSONParser
	{
		String result;
		JSONObject jsonObject;
		JSONArray jsonArray;

		public JSONParser(String response)
		{
			this.result=response;
		}

		public TopUpStatus parse() 
		{
			 
			try 
			{
				jsonObject=new JSONObject(result);
				if(jsonObject.getString("ResponseCode").equals("000"))
                {
					TopUpStatus topUpStatus=new TopUpStatus();
					topUpStatus.setConfirmationCode(jsonObject.getString("ConfirmationCode"));
					topUpStatus.setAuditNo(jsonObject.getString("AuditNo"));
					topUpStatus.setTopUpAmount(jsonObject.getInt("TopUpAmount"));
					
					   System.out.println("=======TopUpStatu========\n"+
                               "Confirmation Code:"+topUpStatus.getConfirmationCode()+
                               "\nAuditNo:"+topUpStatus.getAuditNo()+
                               "\nTopUpAmount:"+topUpStatus.getTopUpAmount());
					   
					   return topUpStatus;	   
                }
				else
				{
					
					handler.post(new Runnable()
					{
						
						public void run() 
						{
							// TODO Auto-generated method stub
							pd.dismiss();
							try 
							{
								Toast.makeText(context, jsonObject.getString("ResponseDescription"),Toast.LENGTH_LONG).show();
							}
							catch (JSONException e)
							{
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					});
					return null;
				}
				
			}
			catch (JSONException e) 
			{
				e.printStackTrace();
				return null;
			}
	 
			
			 
		}
		
	}
}
